import os
from flask import Flask, request, render_template, jsonify

from Util import Util
from database.UserDAO import User,UserDAO

app = Flask(__name__, template_folder="html")

UPLOAD_FOLDER = 'uploads'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['TEMPLATES_AUTO_RELOAD'] = True

@app.route("/")
def go_default():
    return render_template("login.html")

@app.route("/validate", methods=["GET", "POST"])
def validate():
    username_ = request.form.get("username")
    password_ = request.form.get("password")
    user_dao = UserDAO()
    if user_dao.checkUser(username_, password_):
        return "success"
    else:
        return "failed"

@app.route("/file")
def go_file():
    return render_template("FilePage.html")

@app.route('/upload', methods=['POST'])
def upload_file():
    if 'file' not in request.files:
        return jsonify({'message': '没有文件'}), 400
    
    file = request.files['file']
    
    if file.filename == '':
        return jsonify({'message': '没有选择文件'}), 400
    
    if file:
        os.makedirs(UPLOAD_FOLDER, exist_ok=True)
        # 缺陷1：直接使用用户提供的文件名
        filename = file.filename
        # 缺陷2：不检查文件类型
        # 缺陷3：允许路径遍历
        file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
        return jsonify({'message': f'文件 {filename} 上传成功！'})

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=8000, debug=False)